/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 74646
 * Date: 2022-02-20
 * Time: 21:06
 */
 class ListNode {
    public int val;
    public ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public class MyLinkedList {
    int  size;
    ListNode head;
    public MyLinkedList() {
        size = 0;
    }
    public void disPlay(){
        ListNode cur = this.head;
        while (cur!=null){
            System.out.print(cur.val+" ");
            cur = cur.next;

        }
        System.out.println();
    }

    public int get(int index) {
        if(index<0 || index>=size){
            return -1;
        }
        ListNode cur = this.head;
        while(index!=0){
            cur = cur.next;
            index--;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        ListNode node = new ListNode(val);
        node.next = this.head;
        this.head = node;
        size++;
    }

    public void addAtTail(int val) {
        size++;
        ListNode node = new ListNode(val);
        if(this.head==null){
            this.head = node;
        }else {
            ListNode cur = this.head;
            while(cur.next!=null){
                cur = cur.next;
            }
            cur.next = node;
        }

    }

    //找index-1的位置
    public ListNode searchIndex(int index){
        ListNode cur = this.head;
        while(index-1!=0){
            cur = cur.next;
            index--;
        }
        return cur;
    }

    public void addAtIndex(int index, int val) {

        if(index<0 || index>size){
            return;
        }
        if(index==0){
            addAtHead(val);
            return;
        }
        if(index==size){
            addAtTail(val);
            return;
        }
        ListNode node = new ListNode(val);
        ListNode cur = searchIndex(index);
        node.next = cur.next;
        cur.next = node;
        size++;
    }

    public void deleteAtIndex(int index) {

        if(index<0 || index>=size){
            return;
        }
        if(index==0){
            this.head = null;
            size--;
        }else {
            ListNode cur = searchIndex(index);
            cur.next = cur.next.next;
            size--;
        }
    }
}
